<?php
namespace Twoir\Service\Info;

use Config;
use Exception;
use Twoir\Service\BaseInfo;
use Twoir\System\Support\ParamTrait;

/**
 * 信息列表
 *
 * cighsen02 3651872575
 *
 * Create at: 2024.05.03
 * Update at: 2025.05.10
*/
class Lists extends BaseInfo
{
    use ParamTrait;
	// 允许字段
	const ALLOW = ['classid', 'tablename', 'page'];
	// 分页大小
	private int $pageSize;
	// 当前所位置
	private int $currentPage = 1;
	// 默认排序
	private string $orderBy = '';
	// 当次拉取缓存列表
	private $info;
	/**
	 * 栏目id或表名
	 *
	 * @param string|int $classid
	 */
	public function __construct(int|string $classid = null)
	{
		global $public_r;
		//每页数量 默认10
		$this->pageSize = $public_r['qlistinfonum'] ?? 10;

		$this->initialize($classid);
	}

	/**
	 * 获取列表
	 *
	 * @param array $add
	 * @return array
     *
     * @throws Exception
	*/
   public function get(array $add): array
   {
	    global $class_r;

		// 过滤无关参数
		$add = $this->paramFilter($add);

		if (empty($add)) throw new Exception("参数错误!", 9200);

		if (!isset($add['classid']) || empty($add['classid'] = (int)$add['classid'])) {

		    if (!isset($add['tablename']) || empty($add['tablename'])) {

		        throw new Exception("classid或tablename必要参数", 9200);
		    }
		}

		// 每页数量
		if (isset($add['classid'], $class_r[$add['classid']]['lencord']) && $class_r[$add['classid']]['lencord'] && $this->pageSize != $class_r[$add['classid']]['lencord']) {

			$this->pageSize = $class_r[$add['classid']]['lencord'];
		}
		// 默认排序
		if (isset($add['classid'], $class_r[$add['classid']]['reorder']) && $class_r[$add['classid']]['reorder']) {

			$this->orderBy = $class_r[$add['classid']]['reorder'];
		}
		// 当前页
		$this->currentPage = isset($add['page']) && $add['page'] > 1 ? $add['page'] - 1 : 0;
        // 键名采用小驼峰命名
        $modelName  = camel_case($this->modelName());
		// 定义获取的字段
		$field      = Config::twoir('api.' . $modelName . '.list') ?? ['*'];
		// 条件
		$where      = isset($add['classid']) ? $this->getWhere($add['classid']) : [];

		if (0 < $num = $this->getCount($where)) {

			$result = $this->getList($where, $field, '', $this->orderBy, 0, $this->pageSize, $this->currentPage);

			return [
				// 参数说明：询查条件，获取的字段(不写或*表示全部)，分组，排序规则，拉取数量，分页大小，当前页，获取表类型doc、check和正常表
				'list' 			=> $this->format($result),
				'currentpage'	=> ++$this->currentPage,
				'totalpage' 	=> $num > $this->pageSize ? ceil($num / $this->pageSize) : 1
			];
		}

		return [];
    }
}
